<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:56
 */

namespace app\home\controller;

use app\admin\model\Invitation;
use app\home\model\Member;
use think\Cookie;
use think\Loader;
use think\Db;
use think\Log;

class Weixin extends  Base{

/*// 用户授权成功的操作
    public function wxlogin()
    {
        // 当你设置微信回调网址设置为http://your domain/index/weixin/wxlogin时
        // 用户同意授权后，微信后台会访问该网站同时返回code参数
        $config = config('weixin');//获取微信相关配置
        $wechat = new \wxlogin\wxlogin($config);
        $info=['a'=>111,'b'=>222,'c'=>333];
        $data= ['name'=>json_encode($info)];
        Db::name("test")->insert($data);
        if(isset($_GET['code'])){
            // 通过code参数获取Access_Token
            $token = $wechat ->get_access_token($_GET['code']);
            // 通过code参数获取用户信息
            $info = $wechat ->get_userinfo($token->access_token, $token->openid);
            // $info即为已经获得的用户的信息，数据格式为对象形式。如获取用户的openid,获取方式为$info->openid。
            $data= ['name'=>json_encode($info)];
            Db::name("test")->insert($data);
            //你的操作
        }
    }

    // 生成用户登录需要访问的网址
    // 只有进入这个网址，用户才能进行授权
    public function get_authorize_url()
    {
        $config = config('weixin'); // 获取微信相关配置
        $wechat = new \wxlogin\wxlogin($config);
        $url  = $wechat->get_authorize_url('123'); // state为你设置的参数，随便填
        return $url;
    }*/

    private $appid = 'wxa15ade8461bea65c';
    private $appsecret = 'ec2de2e6978d94ff09eadca93e7e381e';
  	public  $Token = '123';
    /**
     * 1、获取微信用户信息，判断有没有code，有使用code换取access_token，没有去获取code。
     * @return array 微信用户信息数组
     */
  
  
  public function valid()

    {

        $echoStr = $_GET["echostr"];


        //valid signature , option

        if($this->checkSignature()){

            echo $echoStr;

            exit;

        }

    }


    public function responseMsg()

    {

        //get post data, May be due to the different environments

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];


        //extract post data

        if (!empty($postStr)){


                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

                $fromUsername = $postObj->FromUserName;

                $toUsername = $postObj->ToUserName;

                $keyword = trim($postObj->Content);

                $time = time();

                $textTpl = "<xml>

                            <ToUserName><![CDATA[%s]]></ToUserName>

                            <FromUserName><![CDATA[%s]]></FromUserName>

                            <CreateTime>%s</CreateTime>

                            <MsgType><![CDATA[%s]]></MsgType>

                            <Content><![CDATA[%s]]></Content>

                            <FuncFlag>0</FuncFlag>

                            </xml>";

                if(!empty( $keyword ))

                {
                    $msgType = "text";

                    $contentStr = "Welcome to wechat world!";

                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);

                    echo $resultStr;

                }else{

                    echo "Input something...";

                }


        }else {

            echo "";

            exit;

        }

    }


    private function checkSignature()

    {

        $signature = $_GET["signature"];

        $timestamp = $_GET["timestamp"];

        $nonce = $_GET["nonce"];


        $token = TOKEN;

        $tmpArr = array($token, $timestamp, $nonce);

        sort($tmpArr);

        $tmpStr = implode( $tmpArr );

        $tmpStr = sha1( $tmpStr );


        if( $tmpStr == $signature ){

            return true;

        }else{

            return false;

        }

    }
  
  
  
  
    public function index(){
        if (!isset($_GET['code'])){//没有code，去微信接口获取code码
            $callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];//微信服务器回调url，这里是本页url
            $this->get_code($callback);
        } else {//获取code后跳转回来到这里了
            $code = $_GET['code'];
            $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
            $data_all = $this->get_user_info($data['access_token'],$data['openid']);//获取微信用户信息
            return $data_all;
        }
    }
    /**
     * 2、用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    private function get_code($callback){
        $appid = $this->appid;
        $scope = 'snsapi_userinfo';
        $state = md5(uniqid(rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        header("Location:$url");
    }
    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    private function get_access_token($code){
        $appid = $this->appid;
        $appsecret = $this->appsecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }
    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    private function get_user_info($access_token,$openid){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }


}